from django.template.context_processors import request
from rest_framework.permissions import BasePermission

from models.models import User
from tools.token_tools import CustomTokenTool


class IsTokenValid():
    """
    自定义权限：仅允许携带有效 Token 的请求访问
    """
    message = "Token 无效或已过期"  # 权限拒绝时的提示
    def has_permission(self, request, view):
        auth_id = request.user.id
        token = request.session.get('auth_token')
        if not token and request.META.get('HTTP_AUTHORIZATION'):
            token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1]

        is_valid, user_id = CustomTokenTool.verify_token(token)

        if not is_valid:
            return False  # Token 无效
        try:
            request.user = User.objects.get(id=user_id)  # 关联当前请求的用户
        except User.DoesNotExist:
            return False
        return True


